import { PLATE_COLOR_MAP } from '@/constants/enums';
import { get } from '@/utils/request';
import { Input, message, Table } from 'antd';
import { useEffect, useMemo, useState } from 'react';

const VehicleCheckboxTable = (props) => {
  const { value, onChange, groupid } = props;
  const [options, setOptions] = useState([]);
  const [license, setLicense] = useState('');

  useEffect(() => {
    const fetchVehicle = async () => {
      try {
        const data = await get('/database/basic/vehicle/listofgroup', {
          groupid,
        });
        setOptions(data);
      } catch (error) {
        console.error('获取车辆数据失败:', error);
        message.error('获取车辆数据失败');
      }
    };

    if (groupid) {
      fetchVehicle();
    } else {
      setOptions([]);
    }
  }, [groupid]);

  const finalOptions = useMemo(() => {
    if (!license) {
      return options;
    }
    return options.filter((item) => item?.license?.includes(license));
  }, [options, license]);
  const columns = [
    {
      title: '车牌号',
      dataIndex: 'license',
      width: 150,
    },
    {
      title: '车牌颜色',
      dataIndex: 'platecolor',
      width: 100,
      render: (text) => PLATE_COLOR_MAP[text],
    },
  ];
  return (
    <div>
      <header style={{ marginBottom: 10 }}>
        <Input.Search
          allowClear
          placeholder="请输入车牌号"
          onSearch={(_value) => setLicense(_value)}
          onChange={(e) => !e.target.value && setLicense('')}
        />
      </header>
      <Table
        rowKey="vehicleid"
        columns={columns}
        dataSource={finalOptions}
        size="small"
        pagination={false}
        scroll={{ y: 200 }}
        virtual
        rowSelection={{
          selectedRowKeys: value,
          onChange: (_selectedRowKeys) => {
            onChange?.(_selectedRowKeys);
          },
        }}
      />
    </div>
  );
};

export default VehicleCheckboxTable;
